#importing the library
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('classic')
plt.style.available
['seaborn-dark',
 'seaborn-darkgrid',
 'seaborn-ticks',
 'fivethirtyeight',
 'seaborn-whitegrid',
 'classic',
 '_classic_test',
 'fast',
 'seaborn-talk',
 'seaborn-dark-palette',
 'seaborn-bright',
 'seaborn-pastel',
 'grayscale',
 'seaborn-notebook',
 'ggplot',
 'seaborn-colorblind',
 'seaborn-muted',
 'seaborn',
 'Solarize_Light2',
 'seaborn-paper',
 'bmh',
 'tableau-colorblind10',
 'seaborn-white',
 'dark_background',
 'seaborn-poster',
 'seaborn-deep']
#%matplotlib inline will lead to static images of your plot embedded in the notebook
%matplotlib inline
import numpy as np
x = np.linspace(0, 10, 100)

fig = plt.figure(figsize=(18,5))
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');
fig.savefig('my_figure.png')
import os
os.getcwd()
'/Users/saurav/Downloads/Python'
from IPython.display import Image
Image('my_figure.png')
fig.canvas.get_supported_filetypes()
{'ps': 'Postscript',
 'eps': 'Encapsulated Postscript',
 'pdf': 'Portable Document Format',
 'pgf': 'PGF code for LaTeX',
 'png': 'Portable Network Graphics',
 'raw': 'Raw RGBA bitmap',
 'rgba': 'Raw RGBA bitmap',
 'svg': 'Scalable Vector Graphics',
 'svgz': 'Scalable Vector Graphics',
 'jpg': 'Joint Photographic Experts Group',
 'jpeg': 'Joint Photographic Experts Group',
 'tif': 'Tagged Image File Format',
 'tiff': 'Tagged Image File Format'}
plt.figure(figsize=(18,6))  # create a plot figure

# create the first of two panels and set current axis
plt.subplot(2, 1, 1) # (rows, columns, panel number)
plt.plot(x, np.sin(x))

# create the second panel and set current axis
plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x));
# First create a grid of plots
# ax will be an array of two Axes objects
fig, ax = plt.subplots(2)

# Call plot() method on the appropriate object
ax[0].plot(x, np.sin(x))
ax[1].plot(x, np.cos(x));
import pandas as pd
df = pd.read_table('https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.data',sep='\s+',header=None)
df.columns = ['seq_name','mcg','gvh','alm','mit','erl','pox','vac','nuc','class']
df.head(3)
seq_name mcg gvh alm mit erl pox vac nuc class
0 ADT1_YEAST 0.58 0.61 0.47 0.13 0.5 0.0 0.48 0.22 MIT
1 ADT2_YEAST 0.43 0.67 0.48 0.27 0.5 0.0 0.53 0.22 MIT
2 ADT3_YEAST 0.64 0.62 0.49 0.15 0.5 0.0 0.53 0.22 MIT
import matplotlib.pyplot as plt
plt.style.use('classic')
import numpy as np

%matplotlib inline
plt.hist(df.mcg) #histogram
plt.show()
# use a gray background
ax = plt.axes(axisbg='#E6E6E6')
ax.set_axisbelow(True)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-0659818c5e74> in <module>
      1 # use a gray background
----> 2 ax = plt.axes(axisbg='#E6E6E6')
      3 ax.set_axisbelow(True)

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in axes(arg, **kwargs)
    875 
    876     if arg is None:
--> 877         return subplot(111, **kwargs)
    878     else:
    879         return gcf().add_axes(arg, **kwargs)

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in subplot(*args, **kwargs)
   1074 
   1075     fig = gcf()
-> 1076     a = fig.add_subplot(*args, **kwargs)
   1077     bbox = a.bbox
   1078     byebye = []

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in add_subplot(self, *args, **kwargs)
   1412                     self._axstack.remove(ax)
   1413 
-> 1414             a = subplot_class_factory(projection_class)(self, *args, **kwargs)
   1415 
   1416         return self._add_axes_internal(key, a)

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_subplots.py in __init__(self, fig, *args, **kwargs)
     67 
     68         # _axes_class is set in the subplot_class_factory
---> 69         self._axes_class.__init__(self, fig, self.figbox, **kwargs)
     70         # add a layout box to this, for both the full axis, and the poss
     71         # of the axis.  We need both because the axes may become smaller

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in __init__(self, fig, rect, facecolor, frameon, sharex, sharey, label, xscale, yscale, **kwargs)
    507             self.set_yscale(yscale)
    508 
--> 509         self.update(kwargs)
    510 
    511         if self.xaxis is not None:

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in update(self, props)
    972 
    973         with cbook._setattr_cm(self, eventson=False):
--> 974             ret = [_update_property(self, k, v) for k, v in props.items()]
    975 
    976         if len(ret):

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in <listcomp>(.0)
    972 
    973         with cbook._setattr_cm(self, eventson=False):
--> 974             ret = [_update_property(self, k, v) for k, v in props.items()]
    975 
    976         if len(ret):

~/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in _update_property(self, k, v)
    968                 if not callable(func):
    969                     raise AttributeError('{!r} object has no property {!r}'
--> 970                                          .format(type(self).__name__, k))
    971                 return func(v)
    972 

AttributeError: 'AxesSubplot' object has no property 'axisbg'
<Figure size 432x288 with 0 Axes>
# draw solid white grid lines
plt.grid(color='w', linestyle='solid')
# hide axis spines
for spine in ax.spines.values():
    spine.set_visible(False)
# hide top and right ticks
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
# lighten ticks and labels
ax.tick_params(colors='gray', direction='out')
for tick in ax.get_xticklabels():
    tick.set_color('gray')
for tick in ax.get_yticklabels():
    tick.set_color('gray')
# control face and edge color of histogram
ax.hist(df.mcg, edgecolor='#E6E6E6', color='#EE6666')
(array([   6.,   54.,  185.,  394.,  403.,  244.,   85.,   78.,   29.,    6.]),
 array([ 0.11 ,  0.199,  0.288,  0.377,  0.466,  0.555,  0.644,  0.733,
         0.822,  0.911,  1.   ]),
 <a list of 10 Patch objects>)
# use a gray background
plt.figure(figsize=(18,5))
ax = plt.axes(axisbg='#E6E6E6')
ax.set_axisbelow(True)

# draw solid white grid lines
plt.grid(color='w', linestyle='solid')

# hide axis spines
for spine in ax.spines.values():
    spine.set_visible(False)
    
# hide top and right ticks
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()

# lighten ticks and labels
ax.tick_params(colors='gray', direction='out')
for tick in ax.get_xticklabels():
    tick.set_color('gray')
for tick in ax.get_yticklabels():
    tick.set_color('gray')
    
# control face and edge color of histogram
ax.hist(df.mcg, edgecolor='#E6E6E6', color='#EE6666');
C:\Users\Mafoi\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:106: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
# runtime configuration (rc)
IPython_default = plt.rcParams.copy()
IPython_default
{'_internal.classic_mode': True,
 'agg.path.chunksize': 0,
 'animation.avconv_args': [],
 'animation.avconv_path': 'avconv',
 'animation.bitrate': -1,
 'animation.codec': 'mpeg4',
 'animation.convert_args': [],
 'animation.convert_path': 'convert',
 'animation.embed_limit': 20.0,
 'animation.ffmpeg_args': [],
 'animation.ffmpeg_path': 'ffmpeg',
 'animation.frame_format': 'png',
 'animation.html': 'none',
 'animation.html_args': [],
 'animation.mencoder_args': [],
 'animation.mencoder_path': 'mencoder',
 'animation.writer': 'ffmpeg',
 'axes.autolimit_mode': 'round_numbers',
 'axes.axisbelow': False,
 'axes.edgecolor': 'k',
 'axes.facecolor': 'w',
 'axes.formatter.limits': [-7, 7],
 'axes.formatter.min_exponent': 0,
 'axes.formatter.offset_threshold': 2,
 'axes.formatter.use_locale': False,
 'axes.formatter.use_mathtext': False,
 'axes.formatter.useoffset': True,
 'axes.grid': False,
 'axes.grid.axis': 'both',
 'axes.grid.which': 'major',
 'axes.hold': None,
 'axes.labelcolor': 'k',
 'axes.labelpad': 5.0,
 'axes.labelsize': 'medium',
 'axes.labelweight': 'normal',
 'axes.linewidth': 1.0,
 'axes.prop_cycle': cycler('color', ['b', 'g', 'r', 'c', 'm', 'y', 'k']),
 'axes.spines.bottom': True,
 'axes.spines.left': True,
 'axes.spines.right': True,
 'axes.spines.top': True,
 'axes.titlepad': 5.0,
 'axes.titlesize': 'large',
 'axes.titleweight': 'normal',
 'axes.unicode_minus': True,
 'axes.xmargin': 0.0,
 'axes.ymargin': 0.0,
 'axes3d.grid': True,
 'backend': 'module://ipykernel.pylab.backend_inline',
 'backend.qt4': 'PyQt4',
 'backend.qt5': 'PyQt5',
 'backend_fallback': True,
 'boxplot.bootstrap': None,
 'boxplot.boxprops.color': 'b',
 'boxplot.boxprops.linestyle': '-',
 'boxplot.boxprops.linewidth': 1.0,
 'boxplot.capprops.color': 'k',
 'boxplot.capprops.linestyle': '-',
 'boxplot.capprops.linewidth': 1.0,
 'boxplot.flierprops.color': 'b',
 'boxplot.flierprops.linestyle': 'none',
 'boxplot.flierprops.linewidth': 1.0,
 'boxplot.flierprops.marker': '+',
 'boxplot.flierprops.markeredgecolor': 'k',
 'boxplot.flierprops.markerfacecolor': 'auto',
 'boxplot.flierprops.markersize': 6.0,
 'boxplot.meanline': False,
 'boxplot.meanprops.color': 'r',
 'boxplot.meanprops.linestyle': '-',
 'boxplot.meanprops.linewidth': 1.0,
 'boxplot.meanprops.marker': 's',
 'boxplot.meanprops.markeredgecolor': 'k',
 'boxplot.meanprops.markerfacecolor': 'r',
 'boxplot.meanprops.markersize': 6.0,
 'boxplot.medianprops.color': 'r',
 'boxplot.medianprops.linestyle': '-',
 'boxplot.medianprops.linewidth': 1.0,
 'boxplot.notch': False,
 'boxplot.patchartist': False,
 'boxplot.showbox': True,
 'boxplot.showcaps': True,
 'boxplot.showfliers': True,
 'boxplot.showmeans': False,
 'boxplot.vertical': True,
 'boxplot.whiskerprops.color': 'b',
 'boxplot.whiskerprops.linestyle': '--',
 'boxplot.whiskerprops.linewidth': 1.0,
 'boxplot.whiskers': 1.5,
 'contour.corner_mask': True,
 'contour.negative_linestyle': 'dashed',
 'datapath': 'C:\\Users\\Mafoi\\Anaconda3\\lib\\site-packages\\matplotlib\\mpl-data',
 'date.autoformatter.day': '%b %d %Y',
 'date.autoformatter.hour': '%H:%M:%S',
 'date.autoformatter.microsecond': '%H:%M:%S.%f',
 'date.autoformatter.minute': '%H:%M:%S.%f',
 'date.autoformatter.month': '%b %Y',
 'date.autoformatter.second': '%H:%M:%S.%f',
 'date.autoformatter.year': '%Y',
 'docstring.hardcopy': False,
 'errorbar.capsize': 3.0,
 'examples.directory': '',
 'figure.autolayout': False,
 'figure.dpi': 72.0,
 'figure.edgecolor': (1, 1, 1, 0),
 'figure.facecolor': (1, 1, 1, 0),
 'figure.figsize': [6.0, 4.0],
 'figure.frameon': True,
 'figure.max_open_warning': 20,
 'figure.subplot.bottom': 0.125,
 'figure.subplot.hspace': 0.2,
 'figure.subplot.left': 0.125,
 'figure.subplot.right': 0.9,
 'figure.subplot.top': 0.9,
 'figure.subplot.wspace': 0.2,
 'figure.titlesize': 'medium',
 'figure.titleweight': 'normal',
 'font.cursive': ['Apple Chancery',
  'Textile',
  'Zapf Chancery',
  'Sand',
  'Script MT',
  'Felipa',
  'cursive'],
 'font.family': ['sans-serif'],
 'font.fantasy': ['Comic Sans MS',
  'Chicago',
  'Charcoal',
  'ImpactWestern',
  'Humor Sans',
  'fantasy'],
 'font.monospace': ['DejaVu Sans Mono',
  'Andale Mono',
  'Nimbus Mono L',
  'Courier New',
  'Courier',
  'Fixed',
  'Terminal',
  'monospace'],
 'font.sans-serif': ['DejaVu Sans',
  'Lucida Grande',
  'Verdana',
  'Geneva',
  'Lucid',
  'Arial',
  'Helvetica',
  'Avant Garde',
  'sans-serif'],
 'font.serif': ['DejaVu Serif',
  'New Century Schoolbook',
  'Century Schoolbook L',
  'Utopia',
  'ITC Bookman',
  'Bookman',
  'Nimbus Roman No9 L',
  'Times New Roman',
  'Times',
  'Palatino',
  'Charter',
  'serif'],
 'font.size': 10.0,
 'font.stretch': 'normal',
 'font.style': 'normal',
 'font.variant': 'normal',
 'font.weight': 'normal',
 'grid.alpha': 1.0,
 'grid.color': 'k',
 'grid.linestyle': ':',
 'grid.linewidth': 0.5,
 'hatch.color': 'k',
 'hatch.linewidth': 1.0,
 'hist.bins': 10,
 'image.aspect': 'equal',
 'image.cmap': 'jet',
 'image.composite_image': True,
 'image.interpolation': 'bilinear',
 'image.lut': 256,
 'image.origin': 'upper',
 'image.resample': False,
 'interactive': True,
 'keymap.all_axes': ['a'],
 'keymap.back': ['left', 'c', 'backspace'],
 'keymap.forward': ['right', 'v'],
 'keymap.fullscreen': ['f', 'ctrl+f'],
 'keymap.grid': ['g'],
 'keymap.grid_minor': ['G'],
 'keymap.home': ['h', 'r', 'home'],
 'keymap.pan': ['p'],
 'keymap.quit': ['ctrl+w', 'cmd+w'],
 'keymap.quit_all': ['W', 'cmd+W', 'Q'],
 'keymap.save': ['s', 'ctrl+s'],
 'keymap.xscale': ['k', 'L'],
 'keymap.yscale': ['l'],
 'keymap.zoom': ['o'],
 'legend.borderaxespad': 0.5,
 'legend.borderpad': 0.4,
 'legend.columnspacing': 2.0,
 'legend.edgecolor': 'inherit',
 'legend.facecolor': 'inherit',
 'legend.fancybox': False,
 'legend.fontsize': 'large',
 'legend.framealpha': None,
 'legend.frameon': True,
 'legend.handleheight': 0.7,
 'legend.handlelength': 2.0,
 'legend.handletextpad': 0.8,
 'legend.labelspacing': 0.5,
 'legend.loc': 'upper right',
 'legend.markerscale': 1.0,
 'legend.numpoints': 2,
 'legend.scatterpoints': 3,
 'legend.shadow': False,
 'lines.antialiased': True,
 'lines.color': 'b',
 'lines.dash_capstyle': 'butt',
 'lines.dash_joinstyle': 'round',
 'lines.dashdot_pattern': [3.0, 5.0, 1.0, 5.0],
 'lines.dashed_pattern': [6.0, 6.0],
 'lines.dotted_pattern': [1.0, 3.0],
 'lines.linestyle': '-',
 'lines.linewidth': 1.0,
 'lines.marker': 'None',
 'lines.markeredgewidth': 0.5,
 'lines.markersize': 6.0,
 'lines.scale_dashes': False,
 'lines.solid_capstyle': 'projecting',
 'lines.solid_joinstyle': 'round',
 'markers.fillstyle': 'full',
 'mathtext.bf': 'serif:bold',
 'mathtext.cal': 'cursive',
 'mathtext.default': 'it',
 'mathtext.fallback_to_cm': True,
 'mathtext.fontset': 'cm',
 'mathtext.it': 'serif:italic',
 'mathtext.rm': 'serif',
 'mathtext.sf': 'sans\\-serif',
 'mathtext.tt': 'monospace',
 'nbagg.transparent': True,
 'patch.antialiased': True,
 'patch.edgecolor': 'k',
 'patch.facecolor': 'b',
 'patch.force_edgecolor': True,
 'patch.linewidth': 1.0,
 'path.effects': [],
 'path.simplify': True,
 'path.simplify_threshold': 0.1111111111111111,
 'path.sketch': None,
 'path.snap': True,
 'pdf.compression': 6,
 'pdf.fonttype': 3,
 'pdf.inheritcolor': False,
 'pdf.use14corefonts': False,
 'pgf.debug': False,
 'pgf.preamble': [],
 'pgf.rcfonts': True,
 'pgf.texsystem': 'xelatex',
 'plugins.directory': '.matplotlib_plugins',
 'polaraxes.grid': True,
 'ps.distiller.res': 6000,
 'ps.fonttype': 3,
 'ps.papersize': 'letter',
 'ps.useafm': False,
 'ps.usedistiller': False,
 'savefig.bbox': None,
 'savefig.directory': '~',
 'savefig.dpi': 100.0,
 'savefig.edgecolor': 'w',
 'savefig.facecolor': 'w',
 'savefig.format': 'png',
 'savefig.frameon': True,
 'savefig.jpeg_quality': 95,
 'savefig.orientation': 'portrait',
 'savefig.pad_inches': 0.1,
 'savefig.transparent': False,
 'scatter.marker': 'o',
 'svg.fonttype': 'path',
 'svg.hashsalt': None,
 'svg.image_inline': True,
 'text.antialiased': True,
 'text.color': 'k',
 'text.hinting': 'auto',
 'text.hinting_factor': 8,
 'text.latex.preamble': [],
 'text.latex.preview': False,
 'text.latex.unicode': False,
 'text.usetex': False,
 'timezone': 'UTC',
 'tk.window_focus': False,
 'toolbar': 'toolbar2',
 'verbose.fileo': 'sys.stdout',
 'verbose.level': 'silent',
 'webagg.open_in_browser': True,
 'webagg.port': 8988,
 'webagg.port_retries': 50,
 'xtick.alignment': 'center',
 'xtick.bottom': True,
 'xtick.color': 'k',
 'xtick.direction': 'in',
 'xtick.labelsize': 'medium',
 'xtick.major.bottom': True,
 'xtick.major.pad': 4.0,
 'xtick.major.size': 4.0,
 'xtick.major.top': True,
 'xtick.major.width': 0.5,
 'xtick.minor.bottom': True,
 'xtick.minor.pad': 4.0,
 'xtick.minor.size': 2.0,
 'xtick.minor.top': True,
 'xtick.minor.visible': False,
 'xtick.minor.width': 0.5,
 'xtick.top': True,
 'ytick.alignment': 'center',
 'ytick.color': 'k',
 'ytick.direction': 'in',
 'ytick.labelsize': 'medium',
 'ytick.left': True,
 'ytick.major.left': True,
 'ytick.major.pad': 4.0,
 'ytick.major.right': True,
 'ytick.major.size': 4.0,
 'ytick.major.width': 0.5,
 'ytick.minor.left': True,
 'ytick.minor.pad': 4.0,
 'ytick.minor.right': True,
 'ytick.minor.size': 2.0,
 'ytick.minor.visible': False,
 'ytick.minor.width': 0.5,
 'ytick.right': True}
#plt.rc function to change configuration
from matplotlib import cycler
colors = cycler('color',
                ['#EE6666', '#3388BB', '#9988DD',
                 '#EECC55', '#88BB44', '#FFBBBB'])
plt.rc('axes', facecolor='#E6E6E6', edgecolor='none',
       axisbelow=True, grid=True, prop_cycle=colors)
plt.rc('grid', color='w', linestyle='solid')
plt.rc('xtick', direction='out', color='gray')
plt.rc('ytick', direction='out', color='gray')
plt.rc('patch', edgecolor='#E6E6E6')
plt.rc('lines', linewidth=2)
plt.hist(df.mcg)
plt.show()
plt.figure(figsize=(18,5))
for i in range(1):
    plt.plot(df.mcg)
plt.figure(figsize=(18,5))
for i in range(2):
    plt.plot(df.mcg)
plt.figure(figsize=(18,5))
for i in range(3):
    plt.plot(df.mcg)
plt.figure(figsize=(18,5))
for i in range(4):
    plt.plot(df.mcg)
plt.figure(figsize=(18,5))
for i in range(5):
    plt.plot(df.mcg)
plt.figure(figsize=(18,5))
for i in range(6):
    plt.plot(df.mcg)
plt.style.available[:5]
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight']
#The basic way to switch to a stylesheet is to call
#plt.style.use('stylename')
#create a function that will make two basic types of plot
def hist_and_lines():
    np.random.seed(0)
    fig, ax = plt.subplots(1, 2, figsize=(18, 4))
    ax[0].hist(df.mcg)
    for i in range(3):
        ax[1].plot(df.mit)
    ax[1].legend(['mit'], loc='upper right')
hist_and_lines()
# reset rcParams
plt.rcParams.update(IPython_default);
with plt.style.context('fivethirtyeight'):
    hist_and_lines()
plt.style.available[:5]
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight']
with plt.style.context('bmh'):
    hist_and_lines()
with plt.style.context('dark_background'):
    hist_and_lines()
with plt.style.context('fast'):
    hist_and_lines()
with plt.style.context('ggplot'):
    hist_and_lines()
#seaborn style
import seaborn as sns
hist_and_lines()
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
fig = plt.figure(figsize=(18,5))
ax = plt.axes()
plt.figure(figsize=(18,5))
plt.plot(df.mcg, color='blue')        # specify color by name
plt.show()
plt.figure(figsize=(18,5))       # short color code (rgbcmyk)
plt.plot(df.mcg, color='g')    
plt.show()
plt.figure(figsize=(18,5))        # Grayscale between 0 and 1
plt.plot(df.mcg, color='0.75')    
plt.show()
plt.figure(figsize=(18,5))        # Hex code (RRGGBB from 00 to FF)
plt.plot(df.mcg, color='#FFDD44')    
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3))    
plt.show()
plt.figure(figsize=(18,5))        # all HTML color names supported
plt.plot(df.mcg, color='chartreuse')    
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='solid') 
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='dashed') 
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='dashdot') 
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='dotted') 
plt.show()
# you can use symbols
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='-') 
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='--') 
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle='-.') 
plt.show()
plt.figure(figsize=(18,5))        # RGB tuple, values 0 to 1
plt.plot(df.mcg, color=(1.0,0.2,0.3),linestyle=':') 
plt.show()
#Adjusting the Plot: Axes Limits
plt.figure(figsize=(18,5)) 
plt.plot(df.mcg, np.square(df.mcg))
plt.xlim(0, 1)
plt.ylim(-0.5, 1.5);
#The plt.axis() method allows you to set the x and y limits with a single call, 
#by passing a list which specifies [xmin, xmax, ymin, ymax]
x = df.gvh
plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.5]);
plt.plot(x, np.sin(x))
plt.axis('tight');
plt.plot(x, np.sin(x))
plt.axis('equal');
#labeling of plots: titles, axis labels, and simple legends
plt.plot(x, np.sin(x))
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)");
plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
plt.axis('equal')

plt.legend();
#plt.xlabel() → ax.set_xlabel()
#plt.ylabel() → ax.set_ylabel()
#plt.xlim() → ax.set_xlim()
#plt.ylim() → ax.set_ylim()
#plt.title() → ax.set_title()
ax = plt.axes()
ax.plot(x, np.sin(x))
ax.set(xlim=(0, 1), ylim=(-2, 2),
       xlabel='x', ylabel='sin(x)',
       title='A Simple Plot');
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1484 entries, 0 to 1483
Data columns (total 10 columns):
seq_name    1484 non-null object
mcg         1484 non-null float64
gvh         1484 non-null float64
alm         1484 non-null float64
mit         1484 non-null float64
erl         1484 non-null float64
pox         1484 non-null float64
vac         1484 non-null float64
nuc         1484 non-null float64
class       1484 non-null object
dtypes: float64(8), object(2)
memory usage: 116.0+ KB
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np
x = df.mcg
y = df.alm
plt.figure(figsize=(18,5))
plt.plot(x, y, 'o', color='black');
plt.figure(figsize=(18,5))
rng = np.random.RandomState(0)
for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']:
    plt.plot(rng.rand(5), rng.rand(5), marker,
             label="marker='{0}'".format(marker))
plt.legend(numpoints=1)
plt.xlim(0, 1.8);
plt.figure(figsize=(18,5))
plt.plot(x, y, '-ok');
plt.figure(figsize=(18,5))
plt.plot(x, y, '-p', color='gray',
         markersize=15, linewidth=4,
         markerfacecolor='white',
         markeredgecolor='gray',
         markeredgewidth=2)
plt.ylim(-1.2, 1.2);
df.info()
#plt.figure(figsize=(18,5))
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1484 entries, 0 to 1483
Data columns (total 10 columns):
seq_name    1484 non-null object
mcg         1484 non-null float64
gvh         1484 non-null float64
alm         1484 non-null float64
mit         1484 non-null float64
erl         1484 non-null float64
pox         1484 non-null float64
vac         1484 non-null float64
nuc         1484 non-null float64
class       1484 non-null object
dtypes: float64(8), object(2)
memory usage: 116.0+ KB
plt.figure(figsize=(18,5))
plt.scatter(df.mcg, df.gvh, marker='o');
#use the alpha keyword to adjust the transparency level:
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.figure(figsize=(18,5))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3,
            cmap='viridis')
plt.colorbar();  # show color scale
from sklearn.datasets import load_iris
iris = load_iris()
features = iris.data.T
plt.figure(figsize=(18,5))
plt.scatter(features[0], features[1], alpha=0.2,
            s=100*features[3], c=iris.target, cmap='viridis')
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1]);
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x2376e995630>
#plt.plot should be preferred over plt.scatter for large datasets due to performance issues
#to display three-dimensional data in two dimensions use contours or color-coded regions
#There are three Matplotlib functions that can be helpful for this task: 
#1.plt.contour for contour plots
#2.plt.contourf for filled contour plots, and 
#3.plt.imshow for showing images
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1484 entries, 0 to 1483
Data columns (total 10 columns):
seq_name    1484 non-null object
mcg         1484 non-null float64
gvh         1484 non-null float64
alm         1484 non-null float64
mit         1484 non-null float64
erl         1484 non-null float64
pox         1484 non-null float64
vac         1484 non-null float64
nuc         1484 non-null float64
class       1484 non-null object
dtypes: float64(8), object(2)
memory usage: 116.0+ KB
X, Y = np.meshgrid(df.mcg, df.gvh)
Z = X + Y
plt.contour(X,Y,Z, colors='black')
<matplotlib.contour.QuadContourSet at 0x2376ea0e358>
plt.contour(X, Y, Z, 20, cmap='RdGy');
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar();
plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
           cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image');
#overplot contours with labels
contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, inline=True, fontsize=8)

plt.imshow(Z, extent=[0, 5, 0, 5], origin='lower',
           cmap='RdGy', alpha=0.5)
plt.colorbar();
#A simple histogram with and without binning
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1484 entries, 0 to 1483
Data columns (total 10 columns):
seq_name    1484 non-null object
mcg         1484 non-null float64
gvh         1484 non-null float64
alm         1484 non-null float64
mit         1484 non-null float64
erl         1484 non-null float64
pox         1484 non-null float64
vac         1484 non-null float64
nuc         1484 non-null float64
class       1484 non-null object
dtypes: float64(8), object(2)
memory usage: 116.0+ KB
plt.hist(df.alm);
plt.hist(df.alm, bins=30, normed=True, alpha=0.5,
         histtype='stepfilled', color='blue',
         edgecolor='none');
# histogram of different columns on one graph from a single dataset
kwargs = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=100)
plt.figure(figsize=(18,6))
plt.hist(df.mcg, **kwargs)
plt.hist(df.gvh, **kwargs)
plt.hist(df.alm, **kwargs);
#plot a two-dimensional histogram is to use Matplotlib's plt.hist2d function
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/bezdekIris.data',header=None)
data.columns = ['sl','sw','pl','pw','class']
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
sl       150 non-null float64
sw       150 non-null float64
pl       150 non-null float64
pw       150 non-null float64
class    150 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9+ KB
plt.figure(figsize=(18,5))
plt.hist2d(data.sl, data.pl, bins=30, cmap='Blues')
cb = plt.colorbar()
cb.set_label('counts in bin')
#plt.hist has a counterpart in np.histogram, plt.hist2d has a counterpart in np.histogram2d
counts, xedges, yedges = np.histogram2d(data.sl, data.pl, bins=30)
plt.figure(figsize=(18,5))
plt.hexbin(data.sl, data.pl, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
import numpy as np
fig, ax = plt.subplots()
ax.plot(data.sl, data.pl, '.b', label='Sl')
ax.plot(data.sw, data.pw, '.r', label='Sw')
ax.axis('equal')
leg = ax.legend();
ax.legend(loc='upper left', frameon=False)
fig
ax.legend(frameon=False, loc='lower center', ncol=2)
fig
ax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)
fig
# 3D plotting using matplotlib
from mpl_toolkits import mplot3d
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
sl       150 non-null float64
sw       150 non-null float64
pl       150 non-null float64
pw       150 non-null float64
class    150 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9+ KB
def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe');
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                cmap='viridis', edgecolor='none')
ax.set_title('surface');
theta = 2 * np.pi * np.random.random(1000)
r = 6 * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax = plt.axes(projection='3d')
ax.scatter(x, y, z, c=z, cmap='viridis', linewidth=0.5);
#Visualization-With-Seaborn, Seaborn provides an API on top of Matplotlib
iris = sns.load_dataset("iris")
iris.head()
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
import seaborn as sns
sns.set()
# same plotting code as above!
plt.plot(iris.sepal_length, iris.sepal_width,'o')
plt.legend('SlSw', ncol=2, loc='upper left');
plt.hist(iris['sepal_length'], normed=True, alpha=0.5)
(array([ 0.16666667,  0.42592593,  0.25925926,  0.5       ,  0.2962963 ,
         0.48148148,  0.33333333,  0.11111111,  0.09259259,  0.11111111]),
 array([ 4.3 ,  4.66,  5.02,  5.38,  5.74,  6.1 ,  6.46,  6.82,  7.18,
         7.54,  7.9 ]),
 <a list of 10 Patch objects>)
sns.kdeplot(iris['sepal_length'], shade=True)
<matplotlib.axes._subplots.AxesSubplot at 0x2374656d588>
data = df
data = pd.DataFrame(data, columns=['mcg', 'gvh', 'alm', 'mit', 'erl', 'pox', 'vac', 'nuc'])
cols = data.columns
for col in cols:
    plt.hist(data[col], normed=True, alpha=0.5)
data = df
data = pd.DataFrame(data, columns=['mcg', 'gvh', 'alm', 'mit', 'erl', 'pox', 'vac', 'nuc'])
cols = data.columns
for col in cols:
    sns.kdeplot(data[col], shade=True)
sns.distplot(data.mcg)
<matplotlib.axes._subplots.AxesSubplot at 0x23756515b70>
sns.distplot(data.alm)
<matplotlib.axes._subplots.AxesSubplot at 0x23756662550>
sns.kdeplot(data)
C:\Users\Mafoi\Anaconda3\lib\site-packages\seaborn\distributions.py:630: UserWarning: Passing a 2D dataset for a bivariate plot is deprecated in favor of kdeplot(x, y), and it will cause an error in future versions. Please update your code.
  warnings.warn(warn_msg, UserWarning)
<matplotlib.axes._subplots.AxesSubplot at 0x23756653f60>
with sns.axes_style('white'):
    sns.jointplot(data.mcg, data.alm, data, kind='kde');
with sns.axes_style('white'):
    sns.jointplot(data.mcg, data.alm, data, kind='hex');
df.info()
sns.pairplot(df, hue='class', size=2.5);
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1484 entries, 0 to 1483
Data columns (total 10 columns):
seq_name    1484 non-null object
mcg         1484 non-null float64
gvh         1484 non-null float64
alm         1484 non-null float64
mit         1484 non-null float64
erl         1484 non-null float64
pox         1484 non-null float64
vac         1484 non-null float64
nuc         1484 non-null float64
class       1484 non-null object
dtypes: float64(8), object(2)
memory usage: 116.0+ KB